﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using ABC.Business.Filters;
using ABC.Business.Models;
using ABC.Controllers.ViewModels.My;
using ABC.Controllers.ViewModels.My.News.Admin;
using ABC.Controllers.ViewModels.My.Partners.Admin;
using ABC.Domain.Entities;

namespace ABC.Controllers.Areas.My
{
    [AdminAuthorize]
    public class AdminController : BaseController
    {
        private readonly NewsModel newsModel;
        private readonly FinanceModel financeModel;
        private readonly RosModel rosModel;
        private readonly PartnerModel partnerModel;
        private readonly RbsCalcModel rbsCalcModel;
        private const int pageSize = 8;

        public AdminController(NewsModel newsModel, RosModel rosModel, FinanceModel financeModel, PartnerModel partnerModel, RbsCalcModel rbsCalcModel)
        {
            this.newsModel = newsModel;
            this.rosModel = rosModel;
            this.financeModel = financeModel;
            this.partnerModel = partnerModel;
            this.rbsCalcModel = rbsCalcModel;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult News(string rubric, string source, string authorId, int? page)
        {
            var model = new NewsManagementViewModel();
            var filters = new Dictionary<string, object>();
            if (!page.HasValue)
            {
                page = 1;
            }
            model.PageNumber = page.Value;
            if (!string.IsNullOrEmpty(rubric))
            {
                filters.Add("Рубрика", rubric);
            }
            if (!string.IsNullOrEmpty(source))
            {
                filters.Add("Источник", source);
            }
            if (!string.IsNullOrEmpty(authorId))
            {
                filters.Add("СсылкаНаАвтора", Convert.ToDecimal(authorId));
            }
            var table = newsModel.GetNewsForAdmin(filters, pageSize, page.Value - 1);
            model.News = table.AsEnumerable().Select(x => new EditNews
                                                           {
                                                               AuthorFullName = string.Format("{0} {1}", rosModel.GetEntityValue<string>(x["СсылкаНаАвтора"].ToString(), "Фамилия"), rosModel.GetEntityValue<string>(x["СсылкаНаАвтора"].ToString(), "Имя")),
                                                               Id = x["id_node"].ToString(),
                                                               IsPublication = Boolean.Parse(x["Опубликовать"].ToString()),
                                                               OwnerId = x["СсылкаНаАвтора"].ToString(),
                                                               Rubric = x["Рубрика"].ToString(),
                                                               TimeOfPublication = DateTime.Parse(x["ДатаПубликации"].ToString()),
                                                               Title = x["НазваниеОбъекта"].ToString(),
                                                               Source = x["Источник"].ToString()
                                                           }).ToList();


            model.PageCount = table.PageCount;
            return View(model);
        }
        [HttpGet]
        public ActionResult Finance(string company, string type, string credit, bool? isarchive, int? page, string pagesize)
        {
            var model = new FinancialPolicyViewModel();
            if (!isarchive.HasValue)
            {
                isarchive = false;
            }
            if (!page.HasValue)
            {
                page = 1;
            }
            if (string.IsNullOrEmpty(pagesize) || pagesize=="0")
            {
                pagesize = model.ListForPageSize.First().Value;
            }
            model.PageNumber = page.Value;
            var currentPolicyItems = financeModel.GetFinancialPolicy(string.IsNullOrEmpty(company) ? model.ListForCompany.First().Value : company).PolicyItems;
            if (!string.IsNullOrEmpty(type))
            {
                currentPolicyItems = currentPolicyItems.Where(x => x.TypeOfInsurance == type).ToList();
            }
            if (!string.IsNullOrEmpty(credit))
            {
                currentPolicyItems = currentPolicyItems.Where(x => x.Credits.Where(y => y.Id == credit && y.Value == "True").Any()).ToList();
            }
            currentPolicyItems = isarchive.Value ? currentPolicyItems.Where(x => x.IsArchive).ToList() : currentPolicyItems.Where(x => !x.IsArchive).ToList();

            model.Finance = currentPolicyItems.Skip((page.Value - 1) * (pagesize != "all" ? Int32.Parse(pagesize) : Int32.MaxValue)).Take((pagesize != "all" ? Int32.Parse(pagesize) : Int32.MaxValue)).ToList();
            model.Finance.ForEach(x => x.Product = rosModel.GetEntityValue<string>(x.Product, "НазваниеОбъекта"));
            model.PageCount = (int)Math.Ceiling((double)currentPolicyItems.Count / (pagesize != "all" ? Int32.Parse(pagesize) : Int32.MaxValue));
            if (model.Finance.Count == 0)
            {
                if (page > 1)
                {
                    page = model.PageCount;
                    return RedirectToAction("Finance", new { page, company, type, credit, isarchive, pagesize });
                }

            }
            return View(model);
        }

        [HttpPost]
        public ActionResult ToArchive(string company, string type, string credit, bool? isarchive, string pagesize, int? page)
        {
            var listId = Request.Form["policyitem"].Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            if (listId.Length > 0)
            {
                var currentPolicyItems = financeModel.GetFinancialPolicy(Request.Form["companyid"]).PolicyItems;
                foreach (var currentPolicyItem in currentPolicyItems.Where(currentPolicyItem => listId.Contains(currentPolicyItem.Id)))
                {
                    currentPolicyItem.IsArchive = true;
                }
                financeModel.SerializeFinancialPolicy(Request.Form["companyid"], currentPolicyItems);
            }
            return RedirectToAction("Finance", new { page, company, type, credit, isarchive, pagesize });
        }

        [HttpPost]
        public ActionResult DeleteRecords(string company, string type, string credit, bool? isarchive, string pagesize, int? page)
        {
            var listId = Request.Form["policyitem"].Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            if (listId.Length > 0)
            {
                var currentPolicyItems = financeModel.GetFinancialPolicy(Request.Form["companyid"]).PolicyItems;
                foreach (var id in listId)
                {
                    currentPolicyItems.Remove(currentPolicyItems.FirstOrDefault(x => x.Id == id));
                }
                financeModel.SerializeFinancialPolicy(Request.Form["companyid"], currentPolicyItems);
            }
            return RedirectToAction("Finance", new { page, company, type, credit, isarchive, pagesize });
        }

        [HttpPost]
        public ActionResult Finance(FinancialPolicyViewModel model, string company, string type, string credit, bool? isarchive, string pagesize, int? page)
        {
            model.PolicyItem.Credits = model.Credits;
            model.PolicyItem.Rewards = model.Rewards;
            model.PolicyItem.SpecialPrograms = model.SpecialPrograms;
            foreach (var reward in model.PolicyItem.Rewards)
            {
                reward.Value = Request.Form[reward.Id];
            }
            if (Request.Form.AllKeys.Contains("specprograms"))
            {
                var specPrograms = Request.Form["specprograms"].Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var specialProgram in model.PolicyItem.SpecialPrograms)
                {
                    specialProgram.Value = specPrograms.Contains(specialProgram.Id) ? "True" : "False";
                }
            }
            if (Request.Form.AllKeys.Contains("selectcredits"))
            {
                var credits = Request.Form["selectcredits"].Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in model.PolicyItem.Credits)
                {
                    item.Value = credits.Contains(item.Id) ? "True" : "False";
                }
            }
            model.PolicyItem.TypeOfInsuranceName = rosModel.GetEntityValue<string>(model.PolicyItem.TypeOfInsurance,
                                                                                   "НазваниеОбъекта");
            model.PolicyItem.CompanyName = rosModel.GetEntityValue<string>(model.PolicyItem.Company,
                                                                                   "НазваниеОбъекта");
            var currentFinancialPolicy = financeModel.GetFinancialPolicy(model.PolicyItem.Company);
            if (currentFinancialPolicy != null)
            {
                model.Finance = currentFinancialPolicy.PolicyItems;
            }
            if (string.IsNullOrEmpty(model.PolicyItem.Id))
            {
                model.PolicyItem.Id = Guid.NewGuid().ToString();
                model.Finance.Add(model.PolicyItem);
            }
            else
            {
                model.Finance.Remove(model.Finance.FirstOrDefault(x => x.Id == model.PolicyItem.Id));
                model.Finance.Add(model.PolicyItem);
            }
            financeModel.SerializeFinancialPolicy(model.PolicyItem.Company, model.Finance);
            pagesize = pagesize == "0" ? "10" : pagesize;
            return RedirectToAction("Finance", new { page, company, type, credit, isarchive, pagesize });
        }

        public ActionResult CopyOrArchiveRecord(string company, string type, string credit, bool? isarchive, string pagesize, int? page)
        {
            var to = Request.Form["to"];
            var currentPolicyItems = financeModel.GetFinancialPolicy(Request.Form["companyid"]).PolicyItems;
            pagesize = pagesize == "0" ? "10" : pagesize;
            switch (to)
            {
                case "archive":
                    var item = currentPolicyItems.FirstOrDefault(x => x.Id == Request.Form["id"]);
                    if (item != null)
                    {
                        item.IsArchive = true;
                    }
                    financeModel.SerializeFinancialPolicy(Request.Form["companyid"], currentPolicyItems);
                    return RedirectToAction("Finance", new { page, company, type, credit, isarchive, pagesize });
                case "copy":
                    var copyItem = currentPolicyItems.FirstOrDefault(x => x.Id == Request.Form["id"]);
                    if (copyItem != null)
                    {
                        copyItem.Id = Guid.NewGuid().ToString();
                        currentPolicyItems.Add(copyItem);
                        var newCurrentPolicyItems = financeModel.GetFinancialPolicy(Request.Form["companyid"]).PolicyItems;
                        newCurrentPolicyItems.Add(copyItem);
                        financeModel.SerializeFinancialPolicy(Request.Form["companyid"], newCurrentPolicyItems);
                    }
                    return RedirectToAction("Finance", new { page, company, type, credit, isarchive, pagesize });
            }
            return RedirectToAction("Finance", new { page, company, type, credit, isarchive, pagesize });
        }

        public ActionResult AddNews(string id)
        {
            var model = new AddNewsViewModel();

            if (string.IsNullOrEmpty(id))
            {
                model.DatePublication = DateTime.Now.ToString("dd.MM.yyyy");
                model.TimePublication = DateTime.Now.ToString("HH:mm");
                model.AuthorFullName = string.Format("{0} {1}", CurrentUser.FirstName, CurrentUser.LastName);
                model.OwnerId = CurrentUser.Id;
            }
            else
            {
                var news = newsModel.GetItemNews(id);
                model.Announcement = news.Announcement;
                model.Id = id;
                model.Content = news.Content;
                model.DatePublication = news.TimeOfPublication.ToString("dd.MM.yyyy");
                model.TimePublication = news.TimeOfPublication.ToString("HH:mm");
                model.Rubric = news.Rubric;
                model.Title = news.Title;
                model.TextForButton = news.TextForButton;
                model.HeaderImage = news.HeaderImage;
                foreach (var tag in news.Tags)
                {
                    model.Tags += string.Format("{0},", tag);
                }
                model.Tags = model.Tags.TrimEnd(',');
                model.OwnerId = rosModel.GetEntityValue<string>(id, "СсылкаНаАвтора");
                model.Source = rosModel.GetEntityValue<string>(id, "Источник");
                var begin = rosModel.GetEntityValue<DateTime>(id, "НачалоДействия").ToString("dd.MM.yyyy");
                var end = rosModel.GetEntityValue<DateTime>(id, "ОкончаниеДействия").ToString("dd.MM.yyyy");
                model.BeginingAction =  begin == DateTime.MinValue.ToString("dd.MM.yyyy") ? "" : begin;
                model.EndAction = end == DateTime.MinValue.ToString("dd.MM.yyyy") ? "" : end;
                model.AuthorFullName = string.Format("{0} {1}", rosModel.GetEntityValue<string>(model.OwnerId, "Имя"),
                                                     rosModel.GetEntityValue<string>(model.OwnerId, "Фамилия"));
                model.IsPublication = rosModel.GetEntityValue<bool>(id, "Опубликовать");
            }
            model.TextForButton = string.IsNullOrEmpty(model.TextForButton) ? "Читать далее" : model.TextForButton;
            var serializer = new JavaScriptSerializer();
            model.TagsTypehead =
                serializer.Serialize(
                    newsModel.GetTags().Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries));
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddNews(AddNewsViewModel model)
        {
            if (ModelState.IsValid)
            {
                var values = new Dictionary<string, object>
                                 {
                                     {"Источник", model.Source},
                                     {"Рубрика", model.Rubric},
                                     {"СсылкаНаАвтора", model.OwnerId},
                                     {"Опубликовать", model.IsPublication},
                                     {"НазваниеОбъекта", model.Title},
                                     {"Анонс",  model.Announcement},
                                     {"Содержимое", HttpUtility.HtmlEncode(model.Content)},
                                     {"ТекстДляКнопки", string.IsNullOrEmpty(model.TextForButton) ? "Читать далее" : model.TextForButton}
                                 };
                DateTime date;
                if (model.Rubric == "Акции и спецпредложения")
                {
                    values.Add("НачалоДействия", DateTime.TryParse(model.BeginingAction, out date) ? date : DateTime.MinValue);
                    values.Add("ОкончаниеДействия", DateTime.TryParse(model.EndAction, out date) ? date : DateTime.MinValue);
                }
                values.Add("ДатаПубликации", DateTime.TryParse(string.Format("{0} {1}", model.DatePublication, model.TimePublication), out date) ? date : DateTime.MinValue);
                var tagsAddedNews = model.Tags.TrimStart(' ').TrimEnd(' ').Replace(";","").Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                var strTagsAddedNews = string.Empty;
                for (var i = 0; i < tagsAddedNews.Length; i++)
                {
                    tagsAddedNews[i] = tagsAddedNews[i].TrimStart(' ').TrimEnd(' ').ToLower();
                    strTagsAddedNews += string.Format("{0};", tagsAddedNews[i]);
                }
                values.Add("Метки", strTagsAddedNews);
                if (!string.IsNullOrEmpty(model.Id))
                {
                    newsModel.UpdateNews(model.Id, values, Request.Files["header-img"], tagsAddedNews);
                    return RedirectToAction("AddNews", new { id = model.Id });
                }
                var newId = newsModel.AddNews(values, Request.Files["header-img"], tagsAddedNews);
                return RedirectToAction("AddNews", new { id = newId });
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult PostData(NewsManagementViewModel model)
        {
            var selectedNewsId = Request.Form["checknews"].Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            if (model.IsDelete)
            {
                newsModel.DeleteNews(selectedNewsId);
            }
            else
            {
                foreach (var id in selectedNewsId)
                {
                    rosModel.UpdateEntityValue(id, "Опубликовать", false);
                }
            }
            return RedirectToAction("News");
        }

        [HttpPost]
        public string Publish(string id, bool isPublic)
        {
            rosModel.UpdateEntityValue(id, "Опубликовать", isPublic);
            return "ok";
        }

        [HttpPost]
        public JsonResult GetPolicyItem(string companyId, string guidId)
        {
            return Json(financeModel.GetFinancialPolicy(companyId).PolicyItems.FirstOrDefault(x => x.Id == guidId));
        }

        public ActionResult Partners(string pagesize, int? page)
        {
            var model = new PartnersManagmentViewModel();
            if (!page.HasValue)
            {
                page = 1;
            }
            if (string.IsNullOrEmpty(pagesize))
            {
                pagesize = model.ListForPageSize.First().Value;
            }
            model.PageNumber = page.Value;
            var table = partnerModel.GetPartnersForAdmin(null, (pagesize != "all" ? Int32.Parse(pagesize) : Int32.MaxValue), page.Value - 1);
            model.Partners = table.AsEnumerable().Select(item => new EditPartner
                                                                     {
                                                                         Name = item["НазваниеОбъекта"].ToString(),
                                                                         Phone = item["НомерТелефона"].ToString(),
                                                                         Id = item["id_node"].ToString(),
                                                                         Fax = item["Факс"].ToString(),
                                                                         FaxDob = item["ФаксДоб"].ToString(),
                                                                         Type = item["Вид"].ToString(),
                                                                         TypeOwnership =
                                                                             item["ФормаСобственности"].ToString()
                                                                     }).ToList();
            model.PageCount = table.PageCount;
            if (model.Partners.Count == 0)
            {
                if (page > 1)
                {
                    page = model.PageCount;
                    return RedirectToAction("Partners", new { page, pagesize });
                }

            }

            return View(model);
        }
        [HttpGet]
        public ActionResult FormPartner(string id, string pagesize, int? page, string ppagesize, int? ppage)
        {
            var model = new AddPartnerViewModel();
            if (!page.HasValue)
            {
                page = 1;
            }
            if (string.IsNullOrEmpty(pagesize))
            {
                pagesize = model.ListForPageSize.First().Value;
            }
            if (!ppage.HasValue)
            {
                ppage = 1;
            }
            if (string.IsNullOrEmpty(ppagesize))
            {
                ppagesize = model.ListForPageSize.First().Value;
            }
            model.PageNumber = page.Value;
            model.PageNumberProducts = ppage.Value;
            if (!string.IsNullOrEmpty(id))
            {
                var partner = partnerModel.GetPartner(id);
                model.Id = id;
                model.Type = partner["Вид"].ToString();
                model.Name = partner["НазваниеОбъекта"].ToString();
                model.FoundationYear = partner["ГодОснования"].ToString();
                model.Phone = partner["НомерТелефона"].ToString();
                model.Fax = partner["Факс"].ToString();
                model.FaxDob = partner["ФаксДоб"].ToString();
                model.Website = partner["ВебСайт"].ToString();
                model.Email = partner["ЭлектроннаяПочта"].ToString();
                model.Socnetwork = partner["СоцСеть"].ToString();
                model.TypeSocnetwork = partner["ТипСоцСеть"].ToString();
                model.FullName = partner["ПолноеНазваниеОбъекта"].ToString();
                model.TypeOwnership = partner["ФормаСобственности"].ToString();
                model.PhoneRequisite = partner["НомерТелефонаРеквизиты"].ToString();
                model.FaxRequisite = partner["ФаксРеквизиты"].ToString();
                model.JuridicalAddress = partner["ЮридическийАдрес"].ToString();
                model.ActualAddress = partner["ФактическийАдрес"].ToString();
                model.Inn = partner["ИНН"].ToString();
                model.Kpp = partner["КПП"].ToString();
                model.Okpo = partner["ОКПО1"].ToString();
                model.PaymentAccount = partner["РасчетныйСчет"].ToString();
                model.CorrespondentAccount = partner["КорреспондентскийСчет"].ToString();
                model.Bik = partner["БИК"].ToString();
                model.Avatar = partner["СсылкаНаАватар"].ToString();
                var serializer = new JavaScriptSerializer();
                var offices = partnerModel.GetPartnerOffices(id, Int32.Parse(pagesize), page.Value - 1);
                model.PageCount = offices.PageCount;
                model.Offices = serializer.Serialize(offices.AsEnumerable().Select(
                                             x =>
                                             new EditOffice
                                             {
                                                 Id = x["id_node"].ToString(),
                                                 Address = x["Адрес"].ToString(),
                                                 Fax = x["Факс"].ToString(),
                                                 FaxDob = x["ФаксДоб"].ToString(),
                                                 Name = x["НазваниеОбъекта"].ToString(),
                                                 Phone = x["НомерТелефона"].ToString(),
                                                 PhoneDob = x["НомерТелефонаДоб"].ToString(),
                                                 Type = x["Тип"].ToString()
                                             }).ToList());
                var products = partnerModel.GetProductsOfPartner(id, Int32.Parse(ppagesize), ppage.Value - 1);
                model.Products = products.AsEnumerable().Select(
                        x =>
                        new EditProduct
                            {
                                Id = x["id_node"].ToString(),
                                Programm = x["НазваниеОбъекта"].ToString(),
                                Type = rosModel.GetEntityValue<string>(x["Тип"].ToString(), "НазваниеОбъекта")
                            }).ToList();
                model.PageCountProducts = products.PageCount;
            }
            else
            {
                model.Offices = "[]";
                model.PageCount = 1;
                model.PageCountProducts = 1;
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult FormPartner(AddPartnerViewModel model)
        {
            var serializer = new JavaScriptSerializer();
            var offices = serializer.Deserialize<List<Office>>(Request.Form["offices"]);
            var deleteOfficesId = serializer.Deserialize<string[]>(Request.Form["deleteOfficesId"]);
            var values = new Dictionary<string, object>
                             {
                                 {"Вид",                    model.Type},
                                 {"НазваниеОбъекта",        model.Name},
                                 {"ГодОснования",           model.FoundationYear},
                                 {"НомерТелефона",          model.Phone},
                                 {"Факс",                   model.Fax},
                                 {"ФаксДоб",                model.FaxDob},
                                 {"ВебСайт",                model.Website},
                                 {"ЭлектроннаяПочта",       model.Email},
                                 {"СоцСеть",                model.Socnetwork},
                                 {"ТипСоцСеть",             model.TypeSocnetwork},
                                 {"ПолноеНазваниеОбъекта",  model.FullName},
                                 {"ФормаСобственности",     model.TypeOwnership},
                                 {"НомерТелефонаРеквизиты", model.PhoneRequisite},
                                 {"ФаксРеквизиты",          model.FaxRequisite},
                                 {"ЮридическийАдрес",       model.JuridicalAddress},
                                 {"ФактическийАдрес",       model.ActualAddress},
                                 {"ИНН",                    model.Inn},
                                 {"КПП",                    model.Kpp},
                                 {"ОКПО1",                  model.Okpo},
                                 {"РасчетныйСчет",          model.PaymentAccount},
                                 {"КорреспондентскийСчет",  model.CorrespondentAccount},
                                 {"БИК",                    model.Bik},
                             };
            if (!string.IsNullOrEmpty(model.Id))
            {
                partnerModel.UpdatePartner(model.Id, values, Request.Files["avatarUpload"], offices, deleteOfficesId);
                return RedirectToAction("Partners");
            }
            model.Id = partnerModel.AddPartner(values, Request.Files["avatarUpload"], offices);
            return RedirectToAction("Partners");

        }
        [HttpPost]
        public string DeletePartnerAvatar(string userId)
        {
            if (string.IsNullOrEmpty(userId))
            {
                return "no";
            }
            partnerModel.DeleteAvatar(partnerModel.GetPartnerAvatar(userId).ToString(), userId);
            return "ok";
        }
        [HttpPost]
        public ActionResult DeletePartner(string id, string pagesize, string page)
        {
            partnerModel.DeletePartner(id);
            return RedirectToAction("Partners", new { page, pagesize });
        }
        [HttpPost]
        public ActionResult DeletePartners(string pagesize, string page, PartnersManagmentViewModel model)
        {
            pagesize = pagesize == "0" ? null : pagesize;
            if (!string.IsNullOrEmpty(Request.Form["companyitem"]))
            {
                var partnersId = Request.Form["companyitem"].Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var id in partnersId)
                {
                    partnerModel.DeletePartner(id);
                }                
            }
            return RedirectToAction("Partners", new { page, pagesize });
        }

        [HttpPost]
        public JsonResult GetOffice(string officeId)
        {
            return Json(partnerModel.GetOffice(officeId));
        }
        [HttpGet]
        public ActionResult FormProduct(string id, string partnerId)
        {
            var model = new AddProductViewModel();
            if (!string.IsNullOrEmpty(id))
            {
                var product = partnerModel.GetProduct(id);
                if (product != null)
                {
                    model.Id = id;
                    model.IsArchive = Boolean.Parse(product["ВАрхиве"].ToString());
                    model.Link = product["СсылкаНаОписание"].ToString();
                    model.Description = product["Описание"].ToString();
                    model.Type = product["Тип"].ToString();
                    model.Name = product["НазваниеОбъекта"].ToString();
                    model.Partner = product["@РодительскийРаздел"].ToString();
                }
            }
            else
            {
                model.Partner = partnerId;
            }
            return View(model);
        }
        [HttpPost]
        public ActionResult FormProduct(AddProductViewModel model)
        {
            var values = new Dictionary<string, object>
                             {
                                 {"Тип", model.Type},
                                 {"ВАрхиве", model.IsArchive},
                                 {"НазваниеОбъекта", model.Name},
                                 {"СсылкаНаОписание", model.Link},
                                 {"Описание", model.Description}
                             };
            if (!string.IsNullOrEmpty(model.Id))
            {
                var idPartner = rosModel.GetEntityValue<decimal>(model.Id, "@РодительскийРаздел").ToString();
                partnerModel.UpdateProduct(model.Id, values);
                return RedirectToAction("FormPartner", new { id = idPartner });
            }
            partnerModel.AddProduct(model.Partner, values);
            return RedirectToAction("FormPartner", new { id = model.Partner });
        }
        public ActionResult DeleteProduct(string productId, string partnerId)
        {
            rosModel.DeleteEntity(productId);
            return RedirectToAction("FormPartner", new { id = partnerId });
        }
        public ActionResult DeleteProducts(string id, string[] productitem)
        {
            foreach (var productId in productitem)
            {
                rosModel.DeleteEntity(productId);
            }
            return RedirectToAction("FormPartner", new { id });
        }

        public JsonResult GetProducts(string partnerId, string typeId)
        {
            var result = financeModel.GetProducts(partnerId, typeId).Select(x => new SelectListItem { Value = x.Key, Text = x.Value }).
                ToList();
            return Json(result, JsonRequestBehavior.AllowGet);
        }

    }
}
